const request = {
	defaultUrl:"http://live.com/",//"域名/",//"",
	defaultApiUrl:null,
	defaultApiPath:null,
	secondApiUrl:null,
	secondApiPath:null,
	useSecondApi:false,
	setHeader:function(params){
		params["url"] = this.defaultUrl + params['url'];
		if(!params["header"]) params["header"] = {};
		params['header']['Content-Type'] = 'application/x-www-form-urlencoded';
		var token =uni.getStorageSync('qu_token');
		if(token) params['header']['token'] = token;
		const info = uni.getSystemInfoSync();
		var uuid = uni.getStorageSync('u_uuid');
		if(!uuid){
			uuid = this.get_uuid();
			uni.setStorageSync("u_uuid",uuid);
		}
		params['header']['device-info'] = info.platform+"-"+uuid;
		return params;
	},
	__init_parms:function(params){
		var success = params["success"];
		var fail = params["fail"];
		params["success"] = (res)=>{
			if(res.data == "no-login" || (typeof res.data !='undefined' && typeof res.data.msg !='undefined' && res.data.msg == "no-login")){
				uni.hideLoading();
				uni.navigateTo({
					url:"/pages/login/login"
				})
				return;
			}
			if(typeof success == 'function') success(res);
		}
		params["fail"] = (res)=>{
			uni.showToast({
				icon:"none",
				title:"网络请求出错"
			});
			if(typeof fail == 'function') fail(res);
		}
		return params;
	},
	post:function(params){
		params = this.setHeader(params);
		params["method"] = "POST";
		params = this.__init_parms(params);
		uni.request(params);
	},
	get:function(params){
		params = this.setHeader(params);
		params["method"] = "GET";
		params = this.__init_parms(params);
		uni.request(params);
	},
	getApiInfo:function(callback,errorCallback){
		uni.request({
			url:this.useSecondApi ? this.secondApiUrl : this.defaultApiUrl,
			success:(res)=>{
				if(typeof callback=='function') callback(res);
			},
			fail:(error)=>{
				if(!this.useSecondApi){
					this.useSecondApi = true;
					this.getApiInfo(callback,errorCallback);
					return;
				}
				if(typeof errorCallback=='function') errorCallback(error);
			}
		});
	},
	getApiList:function(address,callback,errorCallback){
		uni.request({
			url:(this.useSecondApi ? this.secondApiPath :this.defaultApiPath) + address,
			success:(res)=>{
				if(typeof callback=='function') callback(res);
			},
			fail:(error)=>{
				if(typeof errorCallback=='function') errorCallback(error);
			}
		});
	},
	get_uuid:function() {
	    var s = [];
	    var hexDigits = "0123456789abcdef";
	    for (var i = 0; i < 36; i++) {
	        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	    }
	    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	    s[8] = s[13] = s[18] = s[23] = "-";
	
	    var uuid = s.join("");
	    return uuid;
	}
}

module.exports = request